/* eslint-disable import/first */
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('dotenv').config();

import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import cors from '@koa/cors';
import path from 'path';
import { Sequelize } from 'sequelize-typescript';
import jwt from 'koa-jwt';
import loadMiddleware from './middleware';
import routes from './route';
import config from './config';

const app = new Koa();

const sequelize = new Sequelize(
    config.DATABASE.DB.DATABASE,
    config.DATABASE.DB.USERNAME,
    config.DATABASE.DB.PASSWORD,
    {
        host: config.DATABASE.DB.HOST,
        dialect: 'mysql',
    },
);
sequelize.addModels([path.resolve(__dirname, './models/')]);
sequelize.sync();

loadMiddleware(app);

app.use(
    cors({
        origin: '*',
    }),
);

app.use(bodyParser());

app.use(
    jwt({ secret: config.KEYS.secretOrKey }).unless({
        path: ['/register', '/login', '/activate'],
    }),
);

app.use(routes);

app.listen(config.APPLICATION.PORT, () => {
    // eslint-disable-next-line no-console
    console.log(`listen on ${config.APPLICATION.PORT}`);
});
